package user

import (
	"github.com/gin-gonic/gin"
	"go-api-template/api/http"
	"go-api-template/api/models/system"
	"go-api-template/api/ws/front"
	"go-api-template/service"
)

// SaveReq 创建用户
type SaveReq struct {
	UserId   string `json:"user_id"`
	Username string `json:"username" binding:"required"`
	Email    string `json:"email"`
	Phone    int    `json:"phone"`
	Password string `json:"password"`
}
type SaveResp struct {
	ID string `json:"id"`
}

// ListReq 用户列表
type ListReq struct {
	Username string `json:"username"`
	Email    string `json:"email"`
	http.PaginationReq
	http.JobReq
}
type ListResp struct {
	http.RespList[ListRespItem]
}
type ListRespItem struct {
	ID          string             `json:"id"`
	Name        string             `json:"name"`
	Email       string             `json:"email"`
	AllowDelete bool               `json:"allow_delete"`
	IsAdmin     bool               `json:"is_admin"`
	Roles       []ListRespItemRole `json:"roles"`
}
type ListRespItemRole struct {
	RoleId   string `json:"role_id"`
	RoleName string `json:"role_name"`
}

// DeleteReq 删除用户
type DeleteReq struct {
	ID string `json:"id"`
}

// OnlineListReq 在线用户列表
type OnlineListReq struct {
}
type OnlineUsersResp struct {
	http.RespList[OnlineUsersRespItem]
}
type OnlineUsersRespItem struct {
	UserId  string             `json:"user_id"`
	Clients []front.ClientData `json:"clients"`
}

// SetAdminReq 设置为管理员
type SetAdminReq struct {
	UserId string `json:"user_id" binding:"required"`
}
type SetAdminResp struct {
}

// SetRoleReq 设置角色
type SetRoleReq struct {
	UserId  string   `json:"user_id" binding:"required"`
	RoleIds []string `json:"role_ids"`
}
type SetRoleResp struct {
}

func (req *SetRoleReq) Request(ctx *gin.Context, s *service.Service) (http.Resp, error) {
	return req.Do(ctx, s)
}
func (req *SetRoleReq) Do(ctx *gin.Context, s *service.Service) (resp http.Resp, err error) {
	var data SetRoleResp

	s.Db.Unscoped().Where("user_id = ?", req.UserId).Delete(&system.UserRole{})

	var userRoles []system.UserRole
	s.Db.Where("user_id = ?", req.UserId).Find(&userRoles)

	roles, _ := s.RBAC.GetRolesForUser(req.UserId)
	for _, role := range roles {
		_, _ = s.RBAC.DeleteRoleForUser(req.UserId, role)
	}

	for _, id := range req.RoleIds {
		_, _ = s.RBAC.AddRoleForUser(req.UserId, id)
		s.Db.Create(&system.UserRole{
			UserId: req.UserId,
			RoleId: id,
		})
	}

	resp.SetData(data)
	return
}
